﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class GPSStock : ClassManager.SessionManagerPage
    {
        private void GetAllGPS()
        {
            //GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.GpsStock> GpsStockEntities =  GPSTrackingDBV2.Data.DataRepository.GpsStockProvider.GetAll();
            //GPSTrackingDBV2.Data.DataRepository.GpsStockProvider.DeepLoad(GpsStockEntities,true,GPSTrackingDBV2.Data.DeepLoadType.IncludeChildren,typeof(GPSTrackingDBV2.Entities.GpsModels),typeof(GPSTrackingDBV2.Entities.GpsType));

            GPSGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.GPSStockProvider.GetAll();

        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                sdsGPSType.ConnectionString = GPSTrackingDBV2.Data.DataRepository.ConnectionStrings["netTiersConnectionString"].ConnectionString;
                sdsGPSModels.ConnectionString = GPSTrackingDBV2.Data.DataRepository.ConnectionStrings["netTiersConnectionString"].ConnectionString;

                if (!Page.IsPostBack)
                {
                    GridSortExpression expression = new GridSortExpression();
                    expression.FieldName = GPSTrackingDBV2.Entities.GpsStockColumn.Name.ToString();
                    expression.SetSortOrder("Ascending");
                    this.GPSGrid.MasterTableView.SortExpressions.AddSortExpression(expression);                  
                }


            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede iniciar los datos de la sección");
            }
           
        }     

        protected void GPSGrid_InsertCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                GPSTrackingDBV2.Entities.GpsStock GpsStockEntity = ClassManager.InvokeEntityManager.Invoke_GpsStock_Entity(e);

                GPSTrackingDBV2.Data.DataRepository.GpsStockProvider.Insert(GpsStockEntity);
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede insertar la información.");
            }

        }

        protected void GPSGrid_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                GPSTrackingDBV2.Entities.GpsStock GpsStockEntity = ClassManager.InvokeEntityManager.Invoke_GpsStock_Entity(e);

                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                if (Entity["Status"].ToString() == "Pendiente")//No existe, se crea.
                {
                    GPSTrackingDBV2.Data.DataRepository.GpsStockProvider.Insert(GpsStockEntity);
                }
                else {//Ya existe, se actualiza.
                    GpsStockEntity.OriginalGpsImei = GpsStockEntity.GpsImei;

                    GPSTrackingDBV2.Data.DataRepository.GpsStockProvider.Update(GpsStockEntity);
                }

            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede actualizar la información.");
            }
        }

        protected void GPSGrid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            try
            {

                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.GpsStock GpsStockEntity = ClassManager.InvokeEntityManager.Invoke_GpsStock_Entity(e);

                if (Entity["Status"].ToString() == "Registrado")
                {
                    GPSTrackingDBV2.Data.DataRepository.GpsStockProvider.Delete(GpsStockEntity);
                }
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede eliminar el registro porque el dispositivo porque se encuentra asociados a otros registros.");
            }
        }

        protected void GPSGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            try
            {
                GetAllGPS();
                GPSGrid.Height = Unit.Parse(HiddenFieldHeight.Value.ToString());
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("Se ha presentado un error en la carga de los datos"); 
            }
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            GPSGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in GPSGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }

                if (column is GridDropDownColumn)
                {
                    GridDropDownColumn dropDownColumn = column as GridDropDownColumn;
                    dropDownColumn.CurrentFilterValue = string.Empty;
                }
            }

            
            GPSGrid.MasterTableView.Rebind();
        }


        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_miniError", "objWindowsMessageManager.show_miniError('" + msg + "','Dispositivo ...');", true);
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        protected void GPSGrid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.OwnerTableView.IsItemInserted && e.Item.IsInEditMode) //item is about to be inserted  
            {
                TextBox txtid;
                GridEditableItem insertItem = (GridEditableItem)e.Item;
                txtid = (TextBox)insertItem["GpsImei"].Controls[0];
                txtid.ReadOnly = false;
            }
            if (!(e.Item.OwnerTableView.IsItemInserted) && e.Item.IsInEditMode)   //item is about to be edit
            {
                TextBox txtid;
                GridEditableItem insertItem = (GridEditableItem)e.Item;
                txtid = (TextBox)insertItem["GpsImei"].Controls[0];
                txtid.ReadOnly = true;
            } 
        }
    }
}